/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.turn_layout_manager;

import ohos.aafwk.ability.Ability;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;

import java.util.List;
import java.util.Optional;

/**
 * SampleItemProvider
 *
 * @author:hello
 * @since 2021-04-25
 */
public class SampleItemProvider extends BaseItemProvider {
    private Ability slice;
    private List<SampleItem> list;

    /**
     * SampleItemProvider
     *
     * @param slic
     * @param li
     */
    public SampleItemProvider(Ability slic, List<SampleItem> li) {
        this.slice = slic;
        this.list = li;
    }

    /**
     * getCount
     *
     * @return count
     */
    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    /**
     * getItem
     *
     * @param pos
     * @return obj
     */
    @Override
    public Object getItem(int pos) {
        if (list != null && pos >= 0 && pos < list.size()) {
            return list.get(pos);
        }
        return Optional.empty();
    }

    /**
     * getItem
     *
     * @param pos
     * @return pos
     */
    @Override
    public long getItemId(int pos) {
        return pos;
    }

    /**
     * getItem
     *
     * @param pos
     * @param component
     * @param componentContainer
     * @return cpt
     */
    @Override
    public Component getComponent(int pos, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        MyHolder holder;
        if (component == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_item_sample, null, false);
            holder = new MyHolder(cpt);
            cpt.setTag(holder);
        } else {
            cpt = component;
            holder = (MyHolder) cpt.getTag();
        }
        SampleItem sampleItem = list.get(pos);
        holder.text.setText(sampleItem.getName());
        return cpt;
    }

    /**
     * MyHolder
     *
     * @author:hello
     * @since 2021-04-25
     */
    public static class MyHolder {
        private Text text;

        MyHolder(Component component) {
            text = (Text) component.findComponentById(ResourceTable.Id_item_index);
        }
    }
}
